import fetch from '@system.fetch'
let ad_sdk_global = null
let global_data = {
  bannerId: '',
  bannerAd: null,
  nativeBannerIndex: 0,
  nativeBannerArr: [], // 原生banner广告
}
const initBannerSdk = () => {
  ad_sdk_global = AD_SDK.ad_sdk_global
  global_data.bannerId = ad_sdk_global.adNewPostionConfig.ad_banner
  global_data.nativeBannerArr = ad_sdk_global.adNewPostionConfig
    .ad_underpass_origin
    ? ad_sdk_global.adNewPostionConfig.ad_underpass_origin.split(',')
    : []
}
/**
 * ad公共参数
 * @param type 1:横幅；2：原生
 * @param id 原生id
 */
const setCommonParams = (type = 2, obj = {}) => {
  return {
    id: type == 1 ? global_data.bannerId : obj.id,
    ad_network: 1,
    ad_type: type == 1 ? '横幅' : '原生2.0',
    ad_style: '',
    scenario: '厂商广告联盟',
    popName: '底通广告',
    popGroupName: '底通广告',
    type: 'manu_ad',
    scene: '自动请求',
    adTurn: obj.requestNum || 1,
    requestNum: obj.requestNum || 1,
    brand: ad_sdk_global.deviceInfo.brand,
    result: '发起请求'
  }
}
/**
 * 展示banner广告
 * @param obj.success banner广告展示成功回调
 * @param obj.fail banner广告展示失败回调
 */
function getBannerAdv(obj) {
  destroyBannerAdv()
  return new Promise((resolve, reject) => {
    var param = setCommonParams(1, obj)
    let style = {}
    if (
      ad_sdk_global.deviceInfo.brand == 'huawei'
    ) {
      style = {
        width: 360,
        height: 57,
        left: 0,
        top:
          Math.ceil(
            (750 * ad_sdk_global.deviceInfo.screenHeight) /
            ad_sdk_global.deviceInfo.screenWidth
          ) - 67,
      }
    } else if (ad_sdk_global.deviceInfo.brand == 'honor') {
      style = {
        height: 128,
        top: ad_sdk_global.deviceInfo.screenHeight - 280,
        left: 0,
      }
    }

    if (global_data.bannerId) {
      let adParams = {
        adUnitId: global_data.bannerId,
        style: style,
        allowRecommend: true
      }
      global_data.bannerAd =
        ad_sdk_global.serviceAd &&
        require('@service.ad').createBannerAd({
          ...adParams
        })
      console.log(param, 'request------------横幅')
      AD_SDK.uploadAdInfo('request', param)
      if (typeof global_data.bannerAd == 'object') {
        let errFlag = false
        global_data.bannerAd.show()
        global_data.bannerAd.onLoad(() => {
          param.result = '有广告'
          AD_SDK.uploadAdInfo('request', param)
          AD_SDK.uploadAdInfo('show', param)
          AD_SDK.uploadAdInfo('render', param)
          obj && obj.success && obj.success('请求成功')
          resolve('请求成功')
          try {
            global_data.bannerAd.offError()
            global_data.bannerAd.offLoad()
          } catch (error) { }
        })
        global_data.bannerAd.onError((err) => {
          if (errFlag) {
            return
          }
          errFlag = true
          param.result = `无广告${err.errCode ? err.errCode : '错误码获取失败'}`
          AD_SDK.uploadAdInfo('request', param)
          obj && obj.fail && obj.fail('请求失败')
          reject('请求失败')
          try {
            global_data.bannerAd.offError()
            global_data.bannerAd.offLoad()
          } catch (error) { }
        })
      }
    } else {
      obj && obj.fail && obj.fail('没有banner广告id')
      reject('没有banner广告id')
    }
  })
}

/**
 * 隐藏banner广告
 */
function hideBannerAdv() {
  if (global_data.bannerAd) {
    global_data.bannerAd.hide()
  }
}

/**
 * 展示banner广告
 */
function showBannerAdv() {
  if (global_data.bannerAd) {
    global_data.bannerAd.show()
  }
}

/**
 * 销毁banner广告
 */
function destroyBannerAdv() {
  if (global_data.bannerAd) {
    global_data.bannerAd.destroy()
    global_data.bannerAd = null
  }
}
/**
 * 将未被点击的广告对象放回广告池
 * 预加载的情况下才需要把广告放回广告池
 * @param {*} obj 拿出去的广告对象
 */
function setManuAdv(obj) {
  if (obj && obj.id && typeof obj.destroy == 'function') {
    obj.destroy && obj.destroy()
  }
}
/**
 * 取底通原生广告
 */
const getNextBannerId = () => {
  let nativeBannerId = ''
  if (global_data.nativeBannerIndex >= global_data.nativeBannerArr.length) {
    global_data.nativeBannerIndex = 0
  }
  nativeBannerId = global_data.nativeBannerArr[global_data.nativeBannerIndex]
  global_data.nativeBannerIndex++
  return { id: nativeBannerId }
}
/**
 * 底通原生广告
 */
const getBannerNativeAd = async (obj, callback) => {
  //取一个广告位数据
  let nativeAdvConfig = getNextBannerId()
  if (nativeAdvConfig.id) {
    let param = setCommonParams(2, { ...obj, id: nativeAdvConfig.id })
    console.log(param, 'request------------底通原生')
    //获取广告数据
    let results = await new Promise((resolve, reject) => {
      if (
        ad_sdk_global.deviceInfo.brand == 'honor'
      ) {
        AD_SDK.uploadAdInfo('request', param)
        let adParams = {
          adUnitId: nativeAdvConfig.id,
          allowRecommend: true,
          type: 'native',
          adCount: 1
        }
        require('@service.ad').preloadAd({
          ...adParams,
          success: (data) => {
            if (data && data.resultCode === 0 && Array.isArray(data.adInstanceList) && data.adInstanceList.length > 0) {
              let nativeAdvObj = {}
              data.adInstanceList.map((value) => {
                let adObj = value
                nativeAdvObj.adMethod = '0.0'
                nativeAdvObj.advDetail = adObj
                nativeAdvObj.advDetail.adId = nativeAdvObj.advDetail.adid
                nativeAdvObj.desc = nativeAdvObj.advDetail.brand
                nativeAdvObj.title = nativeAdvObj.advDetail.title
                const promotionPurpose = {
                  0: '应用推广',
                  1: '网页推广',
                  2: '应用直达',
                  3: '小程序推广',
                  103: '快应用推广',
                }
                nativeAdvObj.ad_style = promotionPurpose[nativeAdvObj.advDetail.promotionPurpose] || '无'
                nativeAdvObj.clickBtnTxt =
                  nativeAdvObj.advDetail.promotionPurpose == 0
                    ? '安装'
                    : '立即查看'
                nativeAdvObj.materialUrl = AD_SDK.getMaterialUrlByAdData(
                  nativeAdvObj.advDetail
                )
                nativeAdvObj.ad_type = nativeAdvObj.advDetail.hasVideo ? '原生视频2.0' : '原生图片2.0'
                nativeAdvObj.icon = nativeAdvObj.advDetail.logo
                fetch.fetch({
                  url: nativeAdvObj.materialUrl,
                  method: 'get',
                })
              })
              resolve(nativeAdvObj)
            } else {
              if (data && typeof data === 'object') {
                data.errCode = data.resultCode
                data.errMsg = ''
              }
              param.result = AD_SDK.errMsgFormat('无广告', data)
              resolve(false)
            }
          },
          fail: (data) => {
            if (data && typeof data === 'object') {
              data.errCode = data.resultCode
              data.errMsg = ''
            }
            param.result = AD_SDK.errMsgFormat('无广告', data)
            resolve(false)
          },
        })
      } else {
        AD_SDK.uploadAdInfo('request', param)
        let nativeAdvObj =
          ad_sdk_global.serviceAd &&
          require('@service.ad').createNativeAd({
            adUnitId: nativeAdvConfig.id,
          })
        if (typeof nativeAdvObj == 'object') {
          nativeAdvObj.adMethod = '0.0'
          nativeAdvObj &&
            nativeAdvObj.onLoad((res) => {
              if (res && res.adList) {
                nativeAdvObj.advDetail = res.adList[0]
                nativeAdvObj.clickBtnTxt = nativeAdvObj.advDetail.clickBtnTxt
                  ? nativeAdvObj.advDetail.clickBtnTxt
                  : '立即查看'
                if (
                  ad_sdk_global.deviceInfo.brand == 'huawei'
                ) {
                  nativeAdvObj.source = nativeAdvObj.advDetail.title
                  nativeAdvObj.title = nativeAdvObj.advDetail.source
                } else {
                  nativeAdvObj.source = nativeAdvObj.advDetail.desc
                  nativeAdvObj.title = nativeAdvObj.advDetail.title
                }
                const interactionType = {
                  0: '无',
                  1: '链接推广',
                  2: '应用推广',
                  3: '链接推广',
                  4: '打开应用',
                  5: '打开应用',
                }
                nativeAdvObj.ad_style = interactionType[nativeAdvObj.advDetail.interactionType] || '无'
                nativeAdvObj.materialUrl = AD_SDK.getMaterialUrlByAdData(
                  nativeAdvObj.advDetail
                )
                nativeAdvObj.icon = nativeAdvObj.advDetail.icon
                nativeAdvObj.ad_type = '原生0.0'
                fetch.fetch({
                  url: nativeAdvObj.materialUrl,
                  method: 'get',
                })
                nativeAdvObj &&
                  nativeAdvObj.reportAdShow({
                    adId: nativeAdvObj.advDetail.adId,
                  })
                try {
                  nativeAdvObj.offLoad()
                  nativeAdvObj.offError()
                } catch (error) { }
                resolve(nativeAdvObj)
              } else {
                param.result = `底通onload无广告`
                try {
                  nativeAdvObj.offLoad()
                  nativeAdvObj.offError()
                } catch (error) { }
                resolve(false)
              }
            })
          nativeAdvObj.onError((err) => {
            param.result = `无广告${err.errCode ? err.errCode : '错误码获取失败'}`
            try {
              nativeAdvObj.offLoad()
              nativeAdvObj.offError()
              nativeAdvObj.destroy()
            } catch (error) { }
            resolve(false)
          })
          nativeAdvObj.load()
        } else {
          resolve(false)
        }
      }
    })
    LOG('AD', `广告ADSDK========>获取的广告`, results)
    if (results) {
      param.result = '有广告'
      results = Object.assign(results, param, nativeAdvConfig);
      AD_SDK.uploadAdInfo('request', results)
      callback && callback(results)
    } else {
      AD_SDK.uploadAdInfo('request', param)
      callback && callback()
    }
  } else {
    LOG('AD', `广告ADSDK========>无可用广告位ID`)
    callback && callback()
  }
}
/**
    * 通用获取原生广告函数
    * @param {String} ispopShow 当前页面是否展示弹窗
    * @param {String} context   当前页面对象
    */
// 获取底通广告
const getSingleBanner = async (ispopShow = false, _this) => {
  let bannerScale = TACTICS_SDK.getApplyConfig('is_banner_config', 'S', '0.1,0.8,0.1').split(',').map(item => Number(item))
  // 没配置，不启用
  if (bannerScale.length != 3) return
  // 是否过界
  let isCritical = 0
  bannerScale.forEach((item) => {
    isCritical += item
  })
  if (isCritical > 1 || isCritical < 1) {
    bannerScale = [0.4, 0.4, 0.2]
  }
  // 最大比例值
  const bannerScaleMax = Math.max(...bannerScale)
  // 最小比例值
  const bannerScaleMin = Math.min(...bannerScale)
  // 请求位置
  const indexMin = bannerScale.indexOf(bannerScaleMin)
  const indexMax = bannerScale.indexOf(bannerScaleMax)
  const indexMiddle = [0, 1, 2].find((v) => v != indexMin && v != indexMax)
  const ramdomNum = Math.random()
  // 根据随机数与比例选择请求位置
  // const index = ramdomNum < bannerScaleMin ? indexMin : !isNum0 && ramdomNum < bannerScaleMax && !isRepeat ? indexMiddle : indexMax
  const index = ramdomNum < bannerScaleMax ? indexMax : ramdomNum < bannerScaleMax + (1 - bannerScaleMin - bannerScaleMax) ? indexMiddle : indexMin
  return await getBannerInfo(index, ispopShow, _this)
}

/**
* 请求banner广告数据
* @param index 请求广告类型 0->banner 1->原生 2->百度
* @param bannerScale 比例配置[]
*/
const getBannerInfo = async (index, ispopShow, _this) => {
  _this.bannerRequestNum++
  switch (index) {
    case 0:
      AD_SDK.destroyBannerAdv()
      getBannerAdvCommon(_this.bannerRequestNum).then(res => {
        if (ispopShow) {
          AD_SDK.hideBannerAdv()
        }
      }).catch(async err => {
      })
      break
    case 1:
    case 2:
      let adType = index == 1 ? 0 : 3
      let adTimes = 1
      let res = await getManuAdvCommon('厂商广告联盟', 'AD_SCENE_BANNER', adType, adTimes, _this.bannerRequestNum)
      if (res.type == 'success') {
        return res.data
      }
      break
  }
}
/**
  * 通用获取banner广告函数
  */
const getBannerAdvCommon = (requestNum = 1) => {
  return new Promise((resolve, reject) => {
    AD_SDK.getBannerAdv({
      requestNum,
      success: function (res) {
        resolve(res)
      },
      fail: function (err) {
        reject(err)
      }
    })
  })
}
/**
* 通用获取原生广告函数
* @param {String} scenario 广告来源名称
* @param {String} sceneCode 广告场景ID
* @param {String} adType 广告类型 0默认 1原生 2 2.0 3百度
* @param {String} adTimes 广告请求轮数0 1 2
* @param {String} popName 弹窗名称
* @param {String} popGroupName 弹窗组名称
* @param {String} requestNum 广告请求位置 1 2 3
*/
const getManuAdvCommon = (scenario, sceneCode = '', adType = 0, adTimes = 0, requestNum = 1) => {
  let that = this
  console.log('获取广告', ...arguments)
  return new Promise((resolve, reject) => {
    AD_SDK_UTILS.getAd({
      scenario,
      sceneCode,
      adType,
      adTimes,
      requestNum,
      popName: '',
      popGroupName: '',
      success: async function (res) {
        resolve({
          type: 'success',
          data: res
        })
      },
      fail: function (err) {
        resolve({
          type: 'failed',
          data: err
        })
      }
    })
  })
}
export {
  initBannerSdk,
  getBannerAdv,
  showBannerAdv,
  hideBannerAdv,
  destroyBannerAdv,
  setManuAdv,
  getBannerNativeAd,
  getSingleBanner
}
